//
//  WHContactsViewController.m
//  AddressBook
//
//  Created by  on 2020/7/28.
//  Copyright © 2020 wh. All rights reserved.
//

#import "MacroDefinition.h"
#import "WHContactsViewController.h"
#import "WHContactsTableView.h"
#import "WHContactsDetailController.h"
#import "DBHelper.h"
#import "WHContactsEditController.h"
#import "WHUser.h"
#import "WHContactsResultTableView.h"
#import "WHMatchingStrTool.h"
#import "WHContactsEditController.h"
@interface WHContactsViewController ()<WHContactsTableViewDelegate,ResultTableViewDelegate>

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) WHContactsTableView *contactsTableView;
@property (nonatomic, strong) WHContactsResultTableView *resultTableView;

@property (nonatomic, strong) NSMutableArray<NSString *> *nameArr;//通讯录姓名数组
@property (nonatomic, strong) NSMutableArray *sectionTitleArr;//索引数组
@property (nonatomic, strong) NSMutableArray *everSectionArrOfnameArr;//数组类型数组 有所少个单元 每个单元有多少名字

@end

@implementation WHContactsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWithView];
    self.view.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [super setRightBarButtonItemTitle:@"添加"];
    [self update];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification) name:@"notifi" object:nil];
}
#pragma mark - 数据处理
- (void)notification
{
    [self update];
}

- (void)update
{
    [self.contactsTableView removeAllArr];
    [self removeAllArr];
    __weak typeof(self) weakSelf = self;
    [DBHelper searchWithsuccessBlock:^(NSMutableArray * _Nonnull arr) {
        weakSelf.nameArr = [[NSMutableArray alloc] initWithArray:arr];
        [weakSelf initWithNewArr];
        [weakSelf.contactsTableView setDataWithNameArr:weakSelf.nameArr
                                       sectionTitleArr:weakSelf.sectionTitleArr
                               everSectionArrOfnameArr:weakSelf.everSectionArrOfnameArr];
        [weakSelf.contactsTableView reloadData];
    } failureBlock:^(NSString * _Nonnull str) {
        NSLog(@"%@",str);
    }];
}
#pragma mark - 添加视图
- (void)initWithView
{
    [self.view addSubview:self.contactsTableView];
    [self.view addSubview:self.searchTextField];
    [self.view addSubview:self.resultTableView];
    self.resultTableView.hidden = YES;
    
}
#pragma mark - 清楚所有数据
- (void)removeAllArr
{
    if (self.nameArr) {
        [self.nameArr removeAllObjects];
    }
    if (self.sectionTitleArr) {
        [self.sectionTitleArr removeAllObjects];
        self.sectionTitleArr = [NSMutableArray arrayWithArray:[UILocalizedIndexedCollation currentCollation].sectionTitles];
    }
    if (self.everSectionArrOfnameArr) {
        [self.everSectionArrOfnameArr removeAllObjects];
    }
}
#pragma mark - 排序得到按首字母A-Z排列的数组
- (void)initWithNewArr
{
    
    self.everSectionArrOfnameArr = [NSMutableArray array];
    for (NSInteger i = 0; i < self.sectionTitleArr.count; i++) {
        NSMutableArray *nameTmpArr = [NSMutableArray array];
        [self.everSectionArrOfnameArr addObject:nameTmpArr];
    }
    
    NSMutableArray *userArr = [NSMutableArray arrayWithCapacity:self.nameArr.count];
    for (NSString *str in self.nameArr) {
        WHUser *user = [[WHUser alloc] init];
        user.name = str;
        [userArr addObject:user];
    }
    
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    for (WHUser *user in userArr) {
        if (user.name) {
            NSInteger section = [collation sectionForObject:user collationStringSelector:@selector(name)];
            [(NSMutableArray *)self.everSectionArrOfnameArr[section] addObject:user];
        }
    }
    
    for (NSMutableArray *arr in self.everSectionArrOfnameArr) {
        NSArray *sortArr = [collation sortedArrayFromArray:arr collationStringSelector:@selector(name)];
        [arr removeAllObjects];
        [arr addObjectsFromArray:sortArr];
    }
    
    NSMutableArray *tmpArrA = [NSMutableArray array];
    NSMutableArray *tmpArrB = [NSMutableArray array];
    for (NSInteger i = 0; i < self.everSectionArrOfnameArr.count; i++) {
        if (((NSMutableArray *)self.everSectionArrOfnameArr[i]).count == 0) {
            [tmpArrA addObject:self.sectionTitleArr[i]];
            [tmpArrB addObject:self.everSectionArrOfnameArr[i]];
        }
    }
    for (NSInteger i = 0; i < tmpArrA.count; i++) {
        [self.sectionTitleArr removeObject:tmpArrA[i]];
        [self.everSectionArrOfnameArr removeObject:tmpArrB[i]];
    }
}

#pragma mark -  Action
- (void)rightButtonAction
{
    WHContactsEditController *editVC = [[WHContactsEditController alloc] init];
    [self.navigationController pushViewController:editVC animated:NO];
}

- (void)textFieldEditChanged:(UITextField*)textField
{
    NSLog(@"%@",textField.text);
    if (textField.text.length > 0) {
        self.resultTableView.hidden = NO;
        NSString *conditionStr = [WHMatchingStrTool convertToStrWithChineseCharactor:textField.text];
        NSArray *reustArr = [WHMatchingStrTool getIncludeConditionArr:self.nameArr conditionStr:conditionStr];
        [self.resultTableView setContentWithArr:reustArr];
        [self.resultTableView reloadData];
        
    }else{
        self.resultTableView.hidden = YES;
    }
    
}
- (void)resultCellAction:(NSString *)name
{
    WHContactsDetailController *VC = [[WHContactsDetailController alloc] init];
    [VC searchDataWithName:name];
    [self.navigationController pushViewController:VC animated:NO];
}

#pragma mark - delegate
- (void)didSelectRowActionWithCellText:(NSString *)name
{
    WHContactsDetailController *VC = [[WHContactsDetailController alloc] init];
    [VC searchDataWithName:name];
    [self.navigationController pushViewController:VC animated:NO];
}

#pragma mark - 懒加载
- (WHContactsTableView *)contactsTableView
{
    if (!_contactsTableView) {
        _contactsTableView = [[WHContactsTableView alloc] initWithFrame:CGRectMake(0, 160, ScreenWidth, ScreenHeight-160)
                                                                  style:UITableViewStylePlain];
        _contactsTableView.contactsTableViewDelegate = self;
    }
    return _contactsTableView;
}


- (WHContactsResultTableView *)resultTableView
{
    if (!_resultTableView) {
        _resultTableView = [[WHContactsResultTableView alloc] initWithFrame:CGRectMake(0, 160, ScreenWidth, ScreenHeight-160)
                                                                      style:UITableViewStylePlain];
        _resultTableView.resultDelegate = self;
    }
    return _resultTableView;
}
- (UITextField *)searchTextField
{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] init];
        _searchTextField.frame = CGRectMake(5, 100, ScreenWidth-10, 50);
        _searchTextField.layer.borderColor = UIColor.blackColor.CGColor;
        _searchTextField.layer.borderWidth = 2;
        _searchTextField.layer.cornerRadius = 20;
        [_searchTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTextField;
}

- (NSMutableArray<NSString *> *)nameArr
{
    if (!_nameArr) {
        _nameArr = [[NSMutableArray alloc] init];
    }
    return _nameArr;
}
- (NSMutableArray *)everSectionArrOfnameArr
{
    if (!_everSectionArrOfnameArr) {
        _everSectionArrOfnameArr = [[NSMutableArray alloc] init];
    }
    return _everSectionArrOfnameArr;
}
- (NSMutableArray *)sectionTitleArr
{
    if (!_sectionTitleArr) {
        _sectionTitleArr = [NSMutableArray arrayWithArray:[UILocalizedIndexedCollation currentCollation].sectionTitles];
    }
    
    return _sectionTitleArr;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"notifi" object:nil];
}
@end
